package leetcode.L500;

public class EX208 {
//前缀树。
    class TrieNode{
        boolean end;
        TrieNode[] tns = new TrieNode[26];
    }
    TrieNode root;
    /** Initialize your data structure here. */
    public EX208() {
        root = new TrieNode();
    }

    /** Inserts a word into the trie. */
    public void insert(String word) {
        TrieNode p = root;
        for (int i = 0; i < word.length(); i++) {
            int t = word.charAt(i)-'a';
            if(p.tns[t]==null){
                p.tns[t] = new TrieNode();
            }
            p=p.tns[t];
        }
        p.end = true;
    }

    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        TrieNode p = root;
        for (int i = 0; i < word.length(); i++) {
            int t = word.charAt(i)-'a';
            if(p.tns[t]==null){
                return false;
            }
            p = p.tns[t];
        }
        return p.end;
    }

    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        TrieNode p = root;
        for (int i = 0; i < prefix.length(); i++) {
            int t = prefix.charAt(i)-'a';
            if(p.tns[t]==null){
                return false;
            }
            p = p.tns[t];
        }
        return true;
    }
}
